package com.caigou.modules.query.ui.date

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.*
import com.caigou.comm.base.utils.Logger
import com.caigou.comm.base.utils.MediaUtils
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.query.adpter.DateItemAdapter
import com.caigou.modules.query.bean.DateBean
import com.caigou.modules.query.bean.OpenPrizeTimeBean
import com.caigou.modules.query.databinding.ActivityLotteryDateBinding
import com.caigou.modules.query.viewmodel.PrizeDateViewModel
import dagger.hilt.android.AndroidEntryPoint
import java.text.SimpleDateFormat
import java.util.*

/**
 * @author #Suyghur.
 * Created on 2022/01/04
 */
@Route(path = RouterPath.Query.PAGE_LOTTERY_DATE)
@AndroidEntryPoint
class LotteryDateActivity : BaseActivity() {

    private lateinit var binding: ActivityLotteryDateBinding

    private val prizeDateViewModel: PrizeDateViewModel by viewModels()

    private val month = Calendar.getInstance().get(Calendar.MONTH) + 1
    private val year = Calendar.getInstance().get(Calendar.YEAR)
    private val day = Calendar.getInstance().get(Calendar.DATE)
    private val monthDays = mutableListOf<DateBean>()
    private val prizeDates = mutableListOf<Int>()

    private var next = true

    private val mAdapter: DateItemAdapter by lazy {
        DateItemAdapter(mutableListOf())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLotteryDateBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.lotteryDateLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)

        binding.lotteryDateRecyclerView.run {
            layoutManager = GridLayoutManager(this@LotteryDateActivity, 7)
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@LotteryDateActivity))
        }

        binding.lotteryDateTvTime.text = "${year}年${month}月"

        binding.lotteryDateIvRight.visibility = View.VISIBLE
        binding.lotteryDateIvLeft.visibility = View.GONE

        binding.lotteryDateTvBack.setOnClickListener {
            finish()
        }

        binding.lotteryDateIvShare.setOnClickListener {
            val bitmap = binding.lotteryDateLlContainer.screenCapture()
            MediaUtils.saveBitmap(this, bitmap)
            showToast("截图已保存到系统相册")
        }
        prizeDateViewModel.getPrizeDate()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(prizeDateViewModel.prizeDateLiveDate, ::handleGetPrizeDate)
    }

    private fun handleGetPrizeDate(result: Resource<MutableList<OpenPrizeTimeBean>>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取开奖日期异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                result.data?.apply {
                    forEach { bean ->
                        prizeDates.add(ts2time(bean.openPrizeTime)[2].toInt())
                    }
                    handleCalendar()
                    Logger.d(day)
                }
            }
        }
    }

    private fun handleCalendar() {

        monthDays.addAll(getDays(year, month))
        mAdapter.setList(monthDays)

        binding.lotteryDateIvLeft.setOnClickListener {
            if (!next) {
                monthDays.clear()
                monthDays.addAll(getDays(year, month))
                mAdapter.setList(monthDays)
                binding.lotteryDateTvTime.text = "${year}年${month}月"
                binding.lotteryDateIvRight.visibility = View.VISIBLE
                binding.lotteryDateIvLeft.visibility = View.GONE
                next = true
            }
        }

        binding.lotteryDateIvRight.setOnClickListener {
            if (next) {
                var nextYear = 0
                var nextMonth = 0
                if (month == 12) {
                    nextMonth = 1
                    nextYear = year + 1
                } else {
                    nextMonth = month + 1
                    nextYear = year
                }

                monthDays.clear()
                monthDays.addAll(getDays(nextYear, nextMonth))
                mAdapter.setList(monthDays)
                binding.lotteryDateTvTime.text = "${nextYear}年${nextMonth}月"
                binding.lotteryDateIvRight.visibility = View.GONE
                binding.lotteryDateIvLeft.visibility = View.VISIBLE
                next = false
            }
        }
    }

    private fun getDays(y: Int, m: Int): MutableList<DateBean> {
        val week = getFirstWeekOfMonth(y, m - 1)
        val dates = mutableListOf<DateBean>()
        var lastYear = 0
        var lastMonth = 0
        if (m == 1) {
            lastMonth = 12
            lastYear = y - 1
        } else {
            lastMonth = m - 1
            lastYear = y
        }

        val lastMonthDays = getMonthDays(lastYear, lastMonth)
        val currentMonthDays = getMonthDays(y, m)

        var nextYear = 0
        var nextMonth = 0
        if (m == 12) {
            nextMonth = 1
            nextYear = y + 1
        } else {
            nextMonth = m + 1
            nextYear = y
        }

        for (i in 0 until week) {
            dates.add(DateBean(0, lastYear, lastMonth, lastMonthDays - week + 1 + i, false, false))
        }

        for (i in 0 until currentMonthDays) {
            if (m == month) {
                if (i + 1 in prizeDates) {
                    if (i + 1 == day) {
                        dates.add(DateBean(1, y, m, i + 1, true, true))
                    } else {
                        dates.add(DateBean(1, y, m, i + 1, false, true))
                    }
                } else {
                    if (i + 1 == day) {
                        dates.add(DateBean(1, y, m, i + 1, true, false))
                    } else {
                        dates.add(DateBean(1, y, m, i + 1, false, false))
                    }
                }
            } else {
                dates.add(DateBean(1, y, m, i + 1, false, false))
            }
        }

        for (i in 0 until (7 * getMonthRows(y, m) - currentMonthDays - week)) {
            dates.add(DateBean(2, nextYear, nextMonth, i + 1, false, false))
        }
        return dates
    }

    private fun ts2time(ts: Long): List<String> {
        val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.getDefault())
        val time = simpleDateFormat.format(Date(ts))
        return time.split("-")
    }

}